<?php

namespace app\api\service\pay;


use app\api\service\applets\Base;
use app\api\service\lucky\TwiceRward;
use app\common\model\activity\EndlessIncomeLog;
use app\common\model\activity\EndlessIssueLog;
use app\common\model\activity\EndlessLordRecord;
use app\common\model\activity\LuckyBag;
use app\common\model\activity\RewardLog;
use app\common\model\BoxCollect;
use app\common\model\Order;
use app\api\service\coupon\MyCoupon;
use app\common\enum\order\OrderStatus;
use app\common\enum\order\PayStatus;
use app\common\model\activity\EndlessSpecialConfig;
use app\common\model\OrderGoods;
use app\common\model\UserOauth;
use app\common\service\lucky\Endless;
use app\job\LuckyBagEndless;
use app\job\LuckyBagProfit;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;

class EndlessOrderPay extends PaySuccess
{

    private  $order_no = '';
    public function onSuccess(array $payment, int $payType)
    {
        Db::startTrans();
        try{
            //商品更新
            $order = Order::where('order_no', $payment['order_no'])->find();
            $order->pay_status   = PayStatus::SUCCESS;
            $order->trans_no     = $payment['transaction_id'];
            $order->order_status = OrderStatus::COMPLETED;
            $order->pay_time     = time();
            $order->save();
            //统计已售
            $order_goods = OrderGoods::where('order_id',$order->order_id)
                ->select()
                ->toArray();
            $goods_num = array_sum(array_column($order_goods,'total_num'));
            $bag_activity = LuckyBag::where('activity_id',$order->activity_id)->find();
            $bag_activity->sale = Db::raw('sale+'.$goods_num);
            $bag_activity->save();

            //todo 领珠奖处理 --增加记录
            $special_config = EndlessSpecialConfig::where('activity_id',$order->activity_id)->find();
            if($special_config){
                $insert_data = [];
                //处理多数量 拆分商品
                $order_goods_list = $this->processMultipleQuantities($order_goods);
                foreach ($order_goods_list as $order_good){
                    if($order_good['goods_id'] == $special_config->trigger_goods_id){
                        $insert_data[] = [
                            'activity_id' => $order->activity_id,
                            'reward_id' => $special_config->reward_id,
                            'user_id' => $order->user_id,
                            'trigger_goods_id' => $order_good['goods_id'],
                            'order_id' => $order->order_id,
                            'phase_num' => self::getPhaseNum($order->activity_id,$special_config->reward_id),
                        ];
                    }
                }
                if(!empty($insert_data)){
                    (new EndlessLordRecord())->saveAll($insert_data);
                }
                //如果是数量发奖，则此处判断是否满足数量
                if ($special_config->grant_type == 2){
                    $lord_reward_num = EndlessLordRecord::where([
                        'activity_id' => $order->activity_id,
                        'is_sort_cycle' => 1
                    ])->count();
                    if($special_config->grant_num == $lord_reward_num){
                        if($special_config->is_cycle == 0){
                            //不循环
                            $issue_log = EndlessIssueLog::where(['activity_id' => $order->activity_id,'reward_id' => $special_config->reward_id])->find();
                            if(!$issue_log){
                                self::grantRewardFunc($special_config);
                            }
                        }else{
                            //循环
                            self::grantRewardFunc($special_config);
                        }
                    }
                }
            }
            //核销优惠券
            if($order->coupon_id > 0){
                //核销优惠券
                Log::channel('wxpay')->info('无限池订单核销优惠券：'.$order->coupon_id);
                $res = app(MyCoupon::class)->destruction($order->user_id,$order->coupon_id,$order->order_id,$order->coupon_num);
                if(!$res){
                    return false;
                }
            }
            Db::commit();
            $this->order_no = $payment['order_no'];
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            Log::channel('wxpay')->info('订单号：'.$payment['order_no'].'支付失败');
            Log::channel('wxpay')->info('失败原因：'.$e->getMessage());
            return false;
        }
    }

    /**拆分商品 多数量
     * @param $order_goods
     */
    public function processMultipleQuantities($order_goods):array
    {
        $order_goods_list = [];
        foreach ($order_goods as $item) {
            if ($item['total_num'] > 1) {
                $tmp_data = array_pad([$item], $item['total_num'], $item);
                foreach ($tmp_data as $iitem) {
                    array_push($order_goods_list, $iitem);
                }
            } else {
                array_push($order_goods_list, $item);
            }
        }
        return $order_goods_list;
    }


    /**获取当前期数
     * @return mixed|void
     */
    public static function getPhaseNum($activity_id,$reward_id){
        $issue_log_count = EndlessIssueLog::where('activity_id',$activity_id)->where('reward_id',$reward_id)->count();
        $phase_num = 1; //默认为1
        if($issue_log_count > 0){
            $phase_num = $issue_log_count + 1;
        }
        return $phase_num;
    }

    /**发放奖励
     * @param EndlessSpecialConfig $endlessSpecialConfig
     */
    public static function grantRewardFunc(EndlessSpecialConfig $endlessSpecialConfig): bool
    {
        $specialConfig = $endlessSpecialConfig->toArray();
        $special_reward_goods = json_decode($specialConfig['reward'],true);
        $res = app(Endless::class)->issueReward($specialConfig,$special_reward_goods);
        if(!$res){
            return false;
        }
        return true;
    }



    public function callSuccess()
    {
        // 用户订单
        Queue::push("app\\job\\LuckyBagEndless", ['order_no' => $this->order_no], LuckyBagEndless::QUEUE);

    }
}